package com.doge.calcalbum.business.calc

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.ViewGroup
import androidx.core.view.setPadding
import androidx.recyclerview.widget.LinearLayoutManager
import com.doge.calcalbum.R
import com.doge.calcalbum.analysis.analysisEvent
import com.doge.calcalbum.analysis.calc_output
import com.doge.calcalbum.analysis.pwd_pressed_show
import com.doge.calcalbum.api.observeOnMain
import com.doge.calcalbum.api.subscribeOnIO
import com.doge.calcalbum.business.guide.GuideCalcLayout
import com.doge.calcalbum.core.BaseActivity
import com.doge.calcalbum.databinding.ActivityCalcBinding
import com.doge.calcalbum.utils.*
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

class CalcActivity : BaseActivity() {
    private val binding by lazy { ActivityCalcBinding.inflate(layoutInflater) }
    private val adapter by lazy { CalcAdapter() }
    private var heightTask: Disposable? = null
    private var isBackPressed = false
    private var viewGuide: GuideCalcLayout? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        overridePendingTransition(R.anim.anim_keep, R.anim.anims_slide_out_bottom)
        setContentView(binding.root)
        initialViews()
        fixHistoryHeight()
        systemWindowInsetsTop.observe(this) {
            binding.fitsSys.setPadding(it / 2)
        }
        binding.recyclerView.itemAnimator = null
        binding.recyclerView.layoutManager = LinearLayoutManager(binding.recyclerView.context)
        binding.recyclerView.adapter = adapter
        CalcController.history.observe(this) {
            adapter.submitList(it)
        }
        CalcController.output.observe(this) {
            binding.output.text = it
        }
        CalcController.pwdTip.observe(this) {
            binding.tip.text = it ?: ""
        }
        viewGuide = GuideCalcLayout.attach(window.decorView as ViewGroup)
        viewGuide?.setCallback ( object : GuideCalcLayout.Callback {
            override fun invoke(num: Int) = CalcController.input(num.toString())
        })

    }

    private fun fixHistoryHeight() {
        heightTask?.dispose()
        heightTask = Observable.timer(100, TimeUnit.MILLISECONDS)
            .subscribeOnIO()
            .observeOnMain()
            .doOnNext {
                val itemHeight = 40.dp
                val count = binding.recyclerView.height / itemHeight
                val fixHeight = count * itemHeight
                CalcController.setMaxHistoryCount(count)
                binding.recyclerView.layoutParams =
                    binding.recyclerView.layoutParams.apply { height = fixHeight }
            }
            .subscribe()
    }

    override fun finish() {
        super.finish()
        if (!isBackPressed) {
            overridePendingTransition(R.anim.anim_keep, R.anim.anims_slide_out_bottom)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        heightTask?.dispose()
    }

    private fun initialViews() {
        binding.container.setOnClickListener { } // intercept
        binding.num0.setOnClickListener { CalcController.input("0") }
        binding.num1.setOnClickListener { CalcController.input("1") }
        binding.num2.setOnClickListener { CalcController.input("2") }
        binding.num3.setOnClickListener { CalcController.input("3") }
        binding.num4.setOnClickListener { CalcController.input("4") }
        binding.num5.setOnClickListener { CalcController.input("5") }
        binding.num6.setOnClickListener { CalcController.input("6") }
        binding.num7.setOnClickListener { CalcController.input("7") }
        binding.num8.setOnClickListener { CalcController.input("8") }
        binding.num9.setOnClickListener { CalcController.input("9") }
        binding.dot.setOnClickListener { CalcController.input(CalcController.DOT) }
        binding.c.setOnClickListener { CalcController.c() }
        binding.plus.setOnClickListener { CalcController.input(CalcController.PLUS) }
        binding.less.setOnClickListener { CalcController.input(CalcController.LESS) }
        binding.multiply.setOnClickListener { CalcController.input(CalcController.MULTIPLY) }
        binding.divide.setOnClickListener { CalcController.input(CalcController.DIVIDE) }
        binding.delete.setOnClickListener { CalcController.delete() }
        binding.result.setOnClickListener {
            analysisEvent(calc_output)
            CalcController.calc()
        }
        binding.percent.setOnClickListener {
            (viewGuide?.parent as? ViewGroup?)?.removeView(viewGuide)
            CalcController.percent()
        }
        binding.layPlus.setCallback(object : LongTouchLayout.Callback {
            override fun invoke() {
                analysisEvent(pwd_pressed_show)
                toast(CalcPwdHelper.pwd)
            }
        })
    }

    override fun onBackPressed() {
        isBackPressed = true
        Activities.finishAll()
    }

    companion object {
        fun start(context: Activity?) {
            if (context == null) return
            context.startActivity(Intent(context, CalcActivity::class.java).apply {
                if (context == appContext) flags = Intent.FLAG_ACTIVITY_NEW_TASK
            })
            context.overridePendingTransition(0, 0)
        }
    }
}